<template>
    <view class="bg-[var(--page-bg-color)] min-h-[100vh]" :style="themeColor()">
        <view class="w-full bg-[var(--page-bg-color)]">
            <view class="pb-[210rpx] relative" :style="headerStyle">
                <!-- #ifdef MP-WEIXIN || APP-PLUS -->
                <top-tabbar :data="param" :scrollBool="topTabarObj.getScrollBool()" class="top-header" />
                <!-- #endif -->
                <view class="text-[70rpx] leading-[90rpx] text-[#fff] pl-[60rpx] font-500 pt-[77rpx] price-font h-[88rpx]">
                    <!-- {{ info?.contribution_points || 0 }} -->
                </view>
                <view class="flex items-center pl-[60rpx] h-[50rpx]">
                    <!-- <image class="h-[36rpx] w-[36rpx] -mb-[4rpx]" :src="img('static/resource/images/member/point/icon.png')" mode="heightFix" />
                    <view class="text-[26rpx] leading-[36rpx] text-[#fff] ml-[10rpx]">我的贡献值</view> -->
                </view>
                <view class="side-tab" v-if="btnShow" :style="{top: topStyle}" @click="toLink('/app/pages/member/contribution_detail')">
                    <text class="nc-iconfont nc-icon-jifenduihuanV6xx1 icon"></text>
                    <text class="desc">贡献值明细</text>
                </view>
            </view>
            <view class="sidebar-margin flex flex-col mt-[-178rpx] relative">
                <view class="w-[322rpx] h-[80rpx] text-[28rpx] text-[#333] font-500 box-border pl-[30rpx] pt-[var(--pad-top-m)] rounded-tl-[var(--rounded-big)] overflow-hidden mb-[-2rpx]"
                    :style="{backgroundImage: 'url(' + img('static/resource/images/member/point/top_bg.png') + ') ',backgroundSize: '100% 100%',backgroundRepeat: 'no-repeat'}">
                    <text class="leading-[42rpx]">贡献值</text>
                </view>
                <view class="flex items-center px-[30rpx] rounded-[var(--rounded-big)] !rounded-tl-none bg-[#fff] h-[173rpx] box-border">
                    <view class="text-[#333] text-[60rpx] leading-[54rpx] price-font">{{ info?.contribution_points || 0 }}</view>
                </view>
            </view>
        </view>
        
        <view class="mt-[var(--top-m)] sidebar-margin card-template">
        <view class="type-content">
            <view class="type-item checked">兑换</view>
        </view>
        </view>
        <view class="mt-[var(--top-m)] sidebar-margin card-template">
        <view class="title">兑换星星豆数量</view>
        <view class="input-box">
            <input
            v-model.trim="digital_asset"
            type="number"
            placeholder="请输入星星豆数量"
            maxlength="13"
            />
            <view class="btn-right" @click="exchange">全部兑换</view>
        </view>
        <view class="title">兑换说明</view>
            <view class="text-[#999] text-[28rpx] leading-[54rpx] price-font">1.贡献值随时都能兑换黄金珠宝首饰，兑换时需额外支付兑换金额20%的加工费，兑换时需到线下门店兑换。</view>
            <view class="text-[#999] text-[28rpx] leading-[54rpx] price-font">2.贡献值可用于兑换星星豆，兑换比例：{{ buyDigitalAssetsRate || 0 }}:1。</view>
        </view>
        <view class="mt-[var(--top-m)] sidebar-margin bottom-btn" @click="submit"
        >确认兑换</view
        >
    <!-- 支付密码组件 -->
    <pay-local ref="payLocalRef" @success="executeBuy" />
    </view>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import useMemberStore from '@/stores/member'
import useSystemStore from '@/stores/system';
import { redirect, img, pxToRpx } from '@/utils/common';
import { topTabar } from '@/utils/topTabbar'
import { postBuyDigitalAsset, getBuyDigitalAssetsRate } from '@/app/api/member';
import PayLocal from "@/components/pay-local/pay-local.vue";
const systemStore: any = useSystemStore();

const memberStore = useMemberStore()

/********* 自定义头部 - start ***********/
const topTabarObj = topTabar()
let param = topTabarObj.setTopTabbarParam({ title: '贡献值' })
/********* 自定义头部 - end ***********/

// 获取系统状态栏的高度
let menuButtonInfo: any = {};
// 如果是小程序，获取右上角胶囊的尺寸信息，避免导航栏右侧内容与胶囊重叠(支付宝小程序非本API，尚未兼容)
// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ
menuButtonInfo = uni.getMenuButtonBoundingClientRect();
// #endif
const headerStyle = computed(() => {
    return {
        backgroundImage: 'url(' + img('static/resource/images/member/point/contribution_point_bg.png') + ') ',
        backgroundSize: 'cover',
        backgroundRepeat: 'no-repeat',
        backgroundPosition: 'bottom',
        // paddingTop:Object.keys(menuButtonInfo).length?(Number(menuButtonInfo.height) * 2 + menuButtonInfo.top * 2 + 77)+'rpx':'77rpx',
    }
})
const buyDigitalAssetsRate = ref<any>(0); // 贡献值兑换星星豆比例
const topStyle = computed(() => {
    let top = ''
    // #ifdef MP
    top = Object.keys(menuButtonInfo).length ? (pxToRpx(Number(menuButtonInfo.height)) + pxToRpx(menuButtonInfo.top) + 50) + 'rpx;' : '50rpx'
    // #endif
    // #ifdef APP-PLUS
    top =  (systemStore.statusBarHeight + 50) + 'px'
    // #endif
    return top
})
const digital_asset = ref<number>(); // 兑换数量
// 支付密码组件引用
const payLocalRef = ref();

//个人信息
const info = computed(() => {
    return memberStore.info;
})

const btnShow = computed(() => {
    return memberStore.buttonAuth.contribution_point || false;
})

// 获取贡献值兑换星星豆比例
const getBuyDigitalAssetsRateFn = () => {
    getBuyDigitalAssetsRate().then((res: any) => {
        buyDigitalAssetsRate.value = res.data.value || 0;
    });
};

// 全部兑换
const exchange = () => {
    if (buyDigitalAssetsRate.value <= 0) {
        uni.showToast({
        title: "获取兑换星星豆比例失败",
        icon: "none",
        });
        return;
    }
    let val = (info.value?.contribution_points || 1) / (buyDigitalAssetsRate.value || 1);
    digital_asset.value = val;
};


// 提交兑换
const submit = () => {
    if (!info.value.pay_password) {
        uni.showModal({
        title: "提示",
        content: "请先设置支付密码",
        confirmText: "去设置",
        showCancel: false,
        success: (res) => {
            if (res.confirm) {
            redirect({
                url: "/app/pages/paymentSetting/index",
            });
            }
        },
        });
        return;
    }
    
    if (!digital_asset.value || digital_asset.value <= 0) {
        uni.showToast({
        title: "请输入兑换数量",
        icon: "none",
        });
        return;
    }
    let val = (info.value?.contribution_points || 1) / (buyDigitalAssetsRate.value || 1);
    if (digital_asset.value > val) {
        uni.showToast({
        title: "贡献值不足",
        icon: "none",
        });
        return;
    }

    // 弹出支付密码输入框
    payLocalRef.value?.open();
};

// 执行兑换操作
const executeBuy = () => {
    uni.showLoading({
        title: "兑换中...",
        mask: true,
    });
    postBuyDigitalAsset({ digital_asset: digital_asset.value })
        .then((res: any) => {
            digital_asset.value = 0;
        setTimeout(() => {
            uni.showToast({
            title: "兑换成功",
            icon: "none",
            });
        }, 1000);
        memberStore.getMemberInfo();
        })
        .finally(() => {
        uni.hideLoading();
        });
};

const toLink = (url = '', param = {}) => {
    redirect({ url, param })
}

onMounted(() => {
    getBuyDigitalAssetsRateFn();
});
</script>

<style lang="scss" scoped>
.bg-color {
    background-color: rgba(102, 102, 102, 0.4);
}
.bottom-btn {
    z-index: 999;
    text-align: center;
    color: #fff;
    padding: 20rpx;
    border-radius: 20rpx;
    background-color: #ff3e06;
    &:active {
        opacity: 0.8;
    }
}
</style>
